<?php
/**
 * Created by PhpStorm.
 * User: mr_lee
 * Date: 2017/10/31
 * Time: 上午9:12
 */

namespace app\common\controller;


use app\common\model\Merchant;
use app\common\model\Momerchant;
use app\common\model\Paylog;
use think\Controller;

class Pub extends Controller
{
    static function generate_code($length = 50)
    {
        // 密码字符集，可任意添加你需要的字符
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-';
        $code = '';
        for ($i = 0; $i < $length; $i++) {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
            $code .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        $scode = MD5($code . time());
        return $code;
    }
    public function getorderinfo($orderid)
    {
        $map['orderid'] = $orderid;
        $Paylog = new Paylog();

        $payinfo = $Paylog->where($map)->find();
        if (!empty($payinfo['cashier'])) {
            $device_id = $payinfo['cashier'];

        } elseif (!empty($payinfo['d_cashier'])) {
            $device_id = $payinfo['d_cashier'];

        } else {
            $device_id = "";
        }
        $arrc['return_code'] = "SUCCESS";
        $arrc['result_code'] = "SUCCESS";
        $arrc['return_msg'] = "支付成功";
        $arrc['result_msg'] = "支付成功";
        $arrc['out_trade_no'] = $payinfo['orderid'];
        $arrc['trade_no'] = $payinfo['trade_no'];
        $arrc['total_fee'] = $payinfo['price'];//实付金额
        $arrc['channel'] = $payinfo['pay_fs'];//实付金额
        $arrc['merchantname'] = getmerchant($payinfo['mid']);//商户名称
        $arrc['ought_fee'] = $payinfo['yf_price'];//应付金额
        $arrc['gel_fee'] = $payinfo['zk_price'];//折扣金额
        $arrc['dis_card_zk'] = $payinfo['dis_card_zk'];        //会员卡折扣     field('dis_card_zk,vip_card_zk,gel_card_zk,hx_card')->
        $arrc['vip_card_zk'] = $payinfo['vip_card_zk'];        //等级折扣
        $arrc['gel_card_zk'] = $payinfo['gel_card_zk'];        //卡券抵扣
        $arrc['service_charge'] = $payinfo['service_charge'];        //手续费
        $arrc['end_time'] = !empty($payinfo['pay_time']) ? $payinfo['pay_time'] : "";//支付时间
        $arrc['gel_info'] = getdeduzkinfo($payinfo['hx_card'], $payinfo['gel_card_zk']);        //抵扣明细

        $arrc['device_id'] =$device_id;     //收银员
        $arrc['is_vip'] = "";        //是否会员
        $arrc['is_fans'] = "";        //是否粉丝
        $arrc['card_name'] = "";        //会员姓名
        $arrc['card_num'] = "";        //会员卡号

        //推送信息
//        $this->sendorder($orderid);

        return $arrc;


    }
    public function format_price($price)
    {
        $price = (float)$price;//将数值转换为浮点数
        $str = explode(".", $price);//将字符串转换为数组
        if (isset($str[1])) {//判断是否存在小数点
            $str2 = strlen($str[1]);//获取小数点位数
            if ($str2 <= 2) {//当小数点位数小于等于2 原样输出
                $data = $price;
            } else {
                $str4 = substr($str[1], 0, 2);//取出小数点后两位的值
                $str5 = substr($str[1], 0, 1);//取出小数点后1位的值
                if ($str4 == "00") {//当小数点后2为未00时直接+1
                    $str3 = "01";
                } elseif ($str5 == "0") {//当小数点后1为为0时直接最后1位+1
                    if (substr($str[1], 1, 1) + 1 !== 10) {
                        $str3 = (string)$str5 . (substr($str[1], 1, 1) + 1);
                    } else {
                        $str3 = substr($str[1], 0, 1) + 1;
                    }
                } else {//不满足上述条件直接+1
                    $str3 = substr($str[1], 0, 2) + 1;
                }
                if ($str3 == 100) {//当金额为X.99X直接整数+1
                    $data = ($str[0] + 1);
                } else {
                    $data = $str[0] . '.' . $str3;
                }
            }
        } else {
            $data = $price;
        }
        return $data;
    }

    //折扣计算
    public function format_zkprice($price)
    {
        if ($price >= 0.01) {
            $price = (float)$price;//将数值转换为浮点数
            $str = explode(".", $price);//将字符串转换为数组
            if (isset($str[1])) {//判断是否存在小数点
                $str2 = strlen($str[1]);//获取小数点位数
                if ($str2 <= 2) {//当小数点位数小于等于2 原样输出
                    $data = $price;
                } else {
                    $str4 = substr($str[1], 0, 2);//取出小数点后两位的值
                    $str5 = substr($str[1], 0, 1);//取出小数点后1位的值
                    if ($str4 == "00") {//当小数点后2为未00时直接+1
                        $str3 = "01";
                    } elseif ($str5 == "0") {//当小数点后1为为0时直接最后1位+1
                        if (substr($str[1], 1, 1) + 1 !== 10) {
                            $str3 = (string)$str5 . (substr($str[1], 1, 1) + 1);
                        } else {
                            $str3 = substr($str[1], 0, 1) + 1;
                        }
                    } else {//不满足上述条件直接+1
                        $str3 = substr($str[1], 0, 2) + 1;
                    }
                    if ($str3 == 100) {//当金额为X.99X直接整数+1
                        $data = ($str[0] + 1);
                    } else {
                        $data = $str[0] . '.' . $str3;
                    }
                }
            } else {
                $data = $price;
            }
        } else {
            $data = 0;
        }
        return $data;
    }


    public function test2()
    {
        $MchStatis = new MchStatis();

        for ($i = 40; $i >= 1; $i--) {
            $start_time = strtotime(date('Y-m-d')) - 86400 * $i;


            $end_time = $start_time + 86399;
            $statisinfo = $MchStatis->where('statis_times', $start_time)->find();
            if (!$statisinfo) {
                $condition = "p.mid = a.id and  pay_cate <> 'recharge' and p.pay_statu <> 0 and p.pay_statu <> 8 and (p.add_time >= :start_time and p.add_time <= :end_time)";
                $param = ['start_time' => $start_time, 'end_time' => $end_time];
                //微信支付统计
                $condition_1 = $condition . "  and p.pay_fs in (0,2)";
                $field = 'a.id as mid,a.top_mid,a.agent,sum(p.price) as wx_fee,count(p.id) as wx_order';
                $wxpay = $this->statissql($condition_1, $param, $field);
                //支付宝支付统计
                $condition_2 = $condition . "  and p.pay_fs in (1,3)";
                $field = 'a.id as mid,a.top_mid,a.agent,sum(p.price) as ali_fee,count(p.id) as ali_order';
                $alipay = $this->statissql($condition_2, $param, $field);
                //现金支付统计
                $condition_3 = $condition . "  and p.pay_fs = 4";
                $field = 'a.id as mid,a.top_mid,a.agent,sum(p.price) as cash_fee,count(p.id) as cash_order';

                $cashpay = $this->statissql($condition_3, $param, $field);
                //会员卡支付统计
                $condition_4 = $condition . "  and p.pay_fs = 8";
                $field = 'a.id as mid,a.top_mid,a.agent,sum(p.price) as wx_card_fee,count(p.id) as wx_card_order';
                $wxcardpay = $this->statissql($condition_4, $param, $field);
                //折扣 应收 实收统计
                $condition_o = $condition . "";
                $field = 'a.id as mid,sum(p.zk_price) as dis_fee,a.top_mid,a.agent,sum(p.yf_price) as ought_fee,sum(p.price) as real_fee,avg(p.yf_price) as avg_fee';
                $othercount = $this->statissql($condition_o, $param, $field);
                //退款统计
                $Merchant = new Merchant();
                $other2 = $Merchant
                    ->alias('a')
                    ->join('wn_tklog t', 't.mid = a.id and t.tk_status = 1 and (t.addtime >= :start_time and t.addtime <= :end_time)', 'left')
                    ->group('a.id')
                    ->bind($param)
                    ->field('a.id as mid,a.top_mid,a.agent,sum(t.refund_fee) as refund_fee,count(t.id) as refund_order')
                    ->select();

                $infos = array_merge($wxpay, $alipay, $cashpay, $wxcardpay, $othercount, $other2);
                $mchlist = array_unique(array_column($wxpay, 'mid'));
                foreach ($mchlist as $k => $v) {
                    foreach ($infos as $ks => $vs) {
                        if ($vs['mid'] == $v) {
                            $infos2[$k]['mid'] = $vs['mid'];
                            $infos2[$k]['agent'] = $vs['agent'];
                            $infos2[$k]['top_mid'] = $vs['top_mid'];
                            $infos2[$k]['create_time'] = time();
                            $infos2[$k]['statis_time'] = date('Y-m-d H:i:s', $start_time);
                            $infos2[$k]['statis_times'] = $start_time;
                            $infos2[$k]['statis_action'] = 1;
                            if (isset($vs['wx_order'])) {
                                $infos2[$k]['wx_fee'] = !empty($vs['wx_fee']) ? $vs['wx_fee'] : 0.00;
                                $infos2[$k]['wx_order'] = $vs['wx_order'];
                            }
                            if (isset($vs['dis_fee'])) {
                                $infos2[$k]['dis_fee'] = !empty($vs['dis_fee']) ? $vs['dis_fee'] : 0.00;
                                $infos2[$k]['ought_fee'] = !empty($vs['ought_fee']) ? $vs['ought_fee'] : 0.00;
                                $infos2[$k]['avg_fee'] = !empty($vs['avg_fee']) ? $vs['avg_fee'] : 0.00;
                                $infos2[$k]['real_fee'] = !empty($vs['real_fee']) ? $vs['real_fee'] : 0.00;
                            }
                            if (isset($vs['ali_order'])) {
                                $infos2[$k]['ali_fee'] = !empty($vs['ali_fee']) ? $vs['ali_fee'] : 0.00;
                                $infos2[$k]['ali_order'] = $vs['ali_order'];
                            }
                            if (isset($vs['cash_order'])) {
                                $infos2[$k]['cash_fee'] = !empty($vs['cash_fee']) ? $vs['cash_fee'] : 0.00;
                                $infos2[$k]['cash_order'] = $vs['cash_order'];
                            }
                            if (isset($vs['wx_card_order'])) {
                                $infos2[$k]['wx_card_fee'] = !empty($vs['wx_card_fee']) ? $vs['wx_card_fee'] : 0.00;
                                $infos2[$k]['wx_card_order'] = $vs['wx_card_order'];
                            }
                            if (isset($vs['refund_order'])) {

                                $infos2[$k]['refund_fee'] = !empty($vs['refund_fee']) ? $vs['refund_fee'] : 0.00;
                                $infos2[$k]['refund_order'] = $vs['refund_order'];

                            }
                        }


                    }

                }
                $MchStatis = new MchStatis();
                $MchStatis->saveAll($infos2);

            }


        }
    }
    public function exportExcel($merchant,$title = array(), $data = array(), $fileName = '', $sheet = '', $savePath = './', $isDown = false)
    {
        $obj = new \PHPExcel();
//        return $data;

        //横向单元格标识
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        $obj->getActiveSheet(0)->setTitle($sheet);   //设置sheet名称

        $_row = 2;   //设置纵向单元格标识
        if ($title) {
            $_cnt = count($title);
            $obj->getActiveSheet(0)->mergeCells('A'.($_row-1).':'.$cellName[$_cnt-1].($_row-1));   //合并单元格

            $obj->getActiveSheet()->getStyle('A'.($_row-1))->getAlignment()->setWrapText(true);
            $obj->getActiveSheet()->getStyle( 'A'.($_row-1))->getFont()->getColor()->setARGB(\PHPExcel_Style_Color::COLOR_RED);
            $obj->setActiveSheetIndex(0)->setCellValue('A'.($_row-1), '数据导出：'.date('Y-m-d H:i:s').chr(10)."门店:".$merchant);  //设置合并后的单元格内容

            $obj->getActiveSheet()->getRowDimension('1')->setRowHeight(50);
            // $_row++;
            $i = 0;
            foreach ($title AS $v) {   //设置列标题

                $obj->getActiveSheet()->getColumnDimension($cellName[$i])->setWidth('10');
                $obj->setActiveSheetIndex(0)->setCellValue($cellName[$i] . $_row, $v);
//                $obj->getStyle($cellName[$i] . $_row)->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
//                $obj->getStyle($cellName[$i] . $_row)->getFill()->getStartColor->setARGB("#eeeeee");
                $i++;
            }
            $_row++;
        }
        //填写数据
        if ($data) {
            $i = 0;
            foreach ($data AS $_v) {

                $j = 0;
                foreach ($_v AS $_cell) {

                    $obj->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + $_row), $_cell);
                    $j++;
                }
                $i++;
            }
        }



        //文件名处理
        if (!$fileName) {
            $fileName = uniqid(time(), true);
        }

        $objWrite = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');


        if ($isDown) {   //网页下载
            header('pragma:public');
            header("Content-Disposition:attachment;filename=$fileName.xlsx");
            $objWrite->save('php://output');
            exit;
        }

        $_fileName = iconv("utf-8", "gb2312", $fileName);   //转码
        $_savePath =$_fileName . '.xlsx';
        $dir_path="./excel/".date('Y-m-d')."/". $savePath . "/";
        if(!is_dir($dir_path)){
            mkdir($dir_path,0777,true);
        }
        $objWrite->save($dir_path.$_savePath);

        return $dir_path . $fileName . '.xlsx';
    }
    public function sendnotify($mid,$param){

        $Merchant = new Merchant();
        $notify_url=$Merchant->where('id',$mid)->value('notify_url');
        if(!empty($notify_url)){
            $this->http_post($notify_url,$param);
        }


    }
    public function http_post($url, $param, $post_file = false)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')) {
            $is_curlFile = true;
        } else {
            $is_curlFile = false;
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false);
            }
        }
        if (is_string($param)) {
            $strPOST = $param;
        } elseif ($post_file) {

            if ($is_curlFile) {
                foreach ($param as $key => $val) {

                    if (substr($val, 0, 1) == '@') {

                        $param[$key] = new \CURLFile(realpath(substr($val, 1)));

                    }
                }

            }
            $strPOST = $param;

        } else {
            $aPOST = array();
            foreach ($param as $key => $val) {
                $aPOST[] = $key . "=" . urlencode($val);
            }
            $strPOST = join("&", $aPOST);

        }

        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        curl_setopt($oCurl, CURLOPT_HTTPHEADER, array('Content-Type:application/json; charset=utf-8',

            'Content-Length: ' . strlen($param)));
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);

        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }
   

}